package xcity

import (
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 获取区县列表信息
//
//	city_code	市区code
func AreaList(city_code uint) ([]City, error) {
	if city_code%10000 == 0 || city_code%100 != 0 {
		return nil, xerror.New("传入的省份code不正确")
	}
	cache_key := xcache.Key("xcity.area_list", city_code)
	cit := []City{}
	if xcache.Exists(cache_key) {
		if err := xcache.GetStruct(cache_key, &cit); err == nil {
			return cit, nil
		}
		cit = []City{}
	}
	if _default.DB == nil {
		return nil, xerror.New("数据库未连接")
	}
	// 从数据库中进行读取
	err := _default.DB.Table(_default.CityName).
		Where("ad_code > ? and ad_code < ?", city_code, city_code+100).
		Order("ad_code ASC").
		Find(&cit).
		Error
	if err != nil {
		return nil, err
	}
	xcache.SetStruct(cache_key, cit)
	return cit, nil
}
